﻿// MIT License
// 开源地址：https://gitee.com/co1024/AbcMvc
// Copyright (c) 2021-2023 1024
// Abc.Mvc=Furion+EF+SqlSugar+Pear layui admin.



using System.Diagnostics;

namespace Abc.Core.EventBus;

/// <summary>
/// 事件总线订阅执行
/// </summary>
public sealed class EventBusSubscriberExec
{
    /// <summary>
    /// 不线程执行的异步方法
    /// </summary>
    /// <param name="action"></param>
    /// <param name="pess">处理中的事件</param>
    /// <param name="logger">日志</param>
    public static async Task InvokeAsync(Func<Task> action, ProcessingEventSourceStorerDto pess, Serilog.ILogger logger = null)
    {
        if (action == null) throw new ArgumentNullException(nameof(action));

        try
        {
            await action();
            pess.EventSourceStorer.State = EventSourceStorerState.已处理;
        }
        catch (Exception ex)
        {
            //设置处理事件错误
            pess.EventSourceStorer.State = EventSourceStorerState.出现错误;
            pess.EventSourceStorer.Error = ex.Message;

            if (logger == null) logger = AppEx.GetSeriLogger("EventBus\\Subscriber");

            var logstr = $"{pess.EventSourceStorer.ToJson()}\r\n异常：{ex.ToStringEx()}";
            logger.Error(logstr);

            var _logger2 = AppEx.GetSeriLogger("EventBus\\异常日志");
            _logger2.Error(logstr);
            if (Debugger.IsAttached)
            {
                Console.WriteLine(value: $"NotThread.InvokeAsync 出现错误：{ex.Message}");
            }
            throw ex;
        }
        finally
        {
            //设置过期时间，防止重复处理
            EventBusHelper.Instance.SetEventSubscribeCompleted(pess.EventSourceStorer);
        }
    }
}